<template>
  <a-modal
    :maskClosable="maskClosable"
    title="阈值设置"
    :width="600"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form
        ref="form"
        :form="form"
      >
        <a-card
          v-for="d in listData"
          :key="d.meter"
          :title="d.meterCnName"
          style="margin-bottom: 15px"
        >
          <template v-if="!['datacenter_air', 'datacenter_ups'].includes(d.meter)">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="最大值"
            >
              <a-input
                autocomplete="off"
                style="width: 125px"
                :addon-after="d.unit"
                @keyup="clearNoNum('upperThreshold_' + d.id)"
                v-decorator="[
                  'upperThreshold_' + d.id,
                  {
                    initialValue: d.upperThreshold,
                    rules: [
                      { required: true, message: '请输入正数，且最多只能保留两位小数' },
                      { validator: validators.xmax({max:getRange(d.meter).max}), trigger: 'change', },
                      { validator: minValidator({key:('lowerThreshold_' + d.id)}), trigger: 'change', },
                    ],
                    validateFirst: true,
                  },
                ]"
                @blur="(e) => onValChange(e, d.id, 'max', 'upperThreshold_' + d.id)"
              />
              <!-- <a-input-number
                :min="getRange(d.meter).min"
                :max="getRange(d.meter).max"
                :precision="0"
                v-decorator="['upperThreshold_' + d.id, { 
                  initialValue: d.upperThreshold,
                   rules: [
                    { required: true, message: '请输入整数' },
                    { validator: (rule, value, callback) => upperThresholdValidator(rule, value, callback, d.id) }
                  ],
                  validateFirst: true,
                }]"
              />
              <div
                v-if="d.unit"
                class="rule-unit"
              >
                {{d.unit}}
              </div> -->
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="最小值"
            >
              <a-input
                autocomplete="off"
                style="width: 125px"
                :addon-after="d.unit"
                @keyup="clearNoNum('lowerThreshold_' + d.id)"
                v-decorator="[
                  'lowerThreshold_' + d.id,
                  {
                    initialValue: d.lowerThreshold,
                    rules: [
                      { required: true, message: '请输入正数，且最多只能保留两位小数' },
                      { validator: validators.xmin({min:getRange(d.meter).min}), trigger: 'change', },
                      { validator: maxValidator({key:('upperThreshold_' + d.id)}), trigger: 'change', },
                    ],
                    validateFirst: true,
                  },
                ]"
                @blur="(e) => onValChange(e, d.id, 'min', 'lowerThreshold_' + d.id)"
              />
              <!-- <a-input-number
                :min="getRange(d.meter).min"
                :max="getRange(d.meter).max"
                :precision="0"
                v-decorator="['lowerThreshold_' + d.id, {
                  initialValue: d.lowerThreshold, 
                  rules: [
                    { required: true, message: '请输入整数' },
                    { validator: (rule, value, callback) => lowerThresholdValidator(rule, value, callback, d.id) }
                  ],
                  validateFirst: true, 
                }]"
              />
              <div
                v-if="d.unit"
                class="rule-unit"
              >
                {{d.unit}}
              </div> -->
            </a-form-item>
          </template>

          <a-form-item
            v-else
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="阈值"
          >
            <a-input
              autocomplete="off"
              style="width: 125px"
              :addon-after="d.unit"
              @keyup="clearNoNum('upperThreshold_' + d.id, true)"
              @blur="clearNoNum('upperThreshold_' + d.id, true)"
              v-decorator="[
                'upperThreshold_' + d.id,
                {
                  initialValue: d.upperThreshold,
                  rules: [
                    { required: true, message: '请输入正整数' },
                    { validator: validators.xmin({min:getRange(d.meter).min}), trigger: 'change', },
                    { validator: validators.xmax({max:getRange(d.meter).max}), trigger: 'change', },
                  ],
                },
              ]"
            />
            <!-- <a-input-number
              :min="getRange(d.meter).min"
              :max="getRange(d.meter).max"
              :precision="0"
              v-decorator="['upperThreshold_' + d.id, { initialValue: d.upperThreshold, rules: [{ required: true, message: '请输入整数' }] }]"
            />
            <div
              v-if="d.unit"
              class="rule-unit"
            >
              {{d.unit}}
            </div> -->
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="等级"
            style="margin-bottom: 0"
          >
            <a-radio-group v-model="d.level">
              <a-radio
                v-for="l in listLevel"
                :key="l.name"
                :value="l.name"
              >{{
                l.cnName
              }}</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-card>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
  import { gPostAction } from "@/api/manage";
  import { filterNoNum, filterToFloat } from "@/utils/util";
  export default {
    name: "SetThresholdModal",
    data() {
      return {
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        model: {},
        dataCenterList: [],
        threshold: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        typeCnMap: {
          CPU: "计算密集型",
          IO: "磁盘IO密集型",
          AI: "人工智能型",
        },
        listData: [],
        listMeter: [],
        listLevel: [],
        type: "",
        maskClosable: false,
      };
    },
    methods: {
      clearNoNum(fieldName, isThreshold) {
        let obj = {};
        if (isThreshold) {
          obj[fieldName] = filterNoNum(this.form.getFieldValue(fieldName));
        } else {
          obj[fieldName] = filterToFloat(this.form.getFieldValue(fieldName));
        }
        this.form.setFieldsValue(obj);
        this.form.validateFields([fieldName], (errors, values) => {});
      },
      onValChange(e, id, type, _fieldName) {
        if (_fieldName) {
          this.clearNoNum(_fieldName);
        }
        let fieldName = ''
        if (type === 'max') {
          fieldName = 'lowerThreshold_' + id
        } else {
          fieldName = 'upperThreshold_' + id
        }
        let validArr = []
        validArr.push(fieldName)
        this.form.validateFields(validArr)
      },
      minValidator({
        key = ''
      }) {
        // this.form.validateFields([key], (err, values) => {})
        let min = this.form.getFieldValue(key);
        return function (rule, value, callback) {
          let msg = ''
          if (key && min && parseFloat(value) < parseFloat(min)) {
            msg = '最大值不能小于最小值'
          }
          if (msg) {
            callback(msg)
          } else {
            callback()
          }
        }
      },
      maxValidator({
        key = ''
      }) {
        // this.form.validateFields([key], (err, values) => {})
        let max = this.form.getFieldValue(key);
        return function (rule, value, callback) {
          let msg = ''
          if (key && max && parseFloat(value) > parseFloat(max)) {
            msg = '最小值不能大于最大值'
          }
          if (msg) {
            callback(msg)
          } else {
            callback()
          }
        }
      },
      listThresholdMeter() {
        gPostAction("/subhealth/listThresholdMeter", {
          type: this.type,
        }).then((res) => {
          if (res.success && res.data) {
            const meterThresholdMap = {};
            this.listMeter = res.data;
            res.data.forEach((item) => {
              meterThresholdMap[item.meter] = {
                id: "",
                level: "",
                lowerThreshold: "",
                meter: item.meter,
                resourceId: this.model.id,
                type: this.model.type,
                upperThreshold: "",
                meterCnName: item.cnName,
              };
            });
            gPostAction("/subhealth/listThreshold", {
              type: this.type,
            }).then((res) => {
              if (res.success && res.data) {
                res.data.forEach((threshold) => {
                  if (meterThresholdMap[threshold.meter]) {
                    meterThresholdMap[threshold.meter].id = threshold.id;
                    meterThresholdMap[threshold.meter].level = threshold.level;
                    meterThresholdMap[threshold.meter].unit = threshold.unit;
                    let low = threshold.lowerThreshold;
                    let up = threshold.upperThreshold;
                    if (threshold.meter.indexOf('datacenter_') > -1) {
                      meterThresholdMap[threshold.meter].lowerThreshold = low;
                      meterThresholdMap[threshold.meter].upperThreshold = up;
                    } else {
                      if (low === 0) {
                        meterThresholdMap[threshold.meter].lowerThreshold = parseFloat('0').toFixed(2);
                      } else {
                        meterThresholdMap[threshold.meter].lowerThreshold = low ? parseFloat(low).toFixed(2) : '';
                      }
                      meterThresholdMap[threshold.meter].upperThreshold = up ? parseFloat(up).toFixed(2) : '';
                    }
                  }
                });
              }
              Object.keys(meterThresholdMap).forEach((key) => {
                this.listData.push(meterThresholdMap[key]);
              });
            });
          }
        });
      },
      listAlertLevel() {
        gPostAction("/subhealth/listAlertLevel", {}).then((res) => {
          if (res.success && res.data) {
            this.listLevel = res.data;
          }
        });
      },
      set(type) {
        this.listData = [];
        this.listMeter = [];
        this.listLevel = [];
        this.type = type;
        this.listAlertLevel();
        this.listThresholdMeter();
        this.visible = true;
      },
      handleOk() {
        this.form.validateFields((err, values) => {
          if (!err) {
            this.confirmLoading = true;
            const postData = {};
            // postData.resourceId = this.model.id;
            postData.type = this.type;
            let index = 0;
            this.listData.forEach((item) => {
              postData["subhealthThresholds[" + index + "].id"] = item.id;
              postData["subhealthThresholds[" + index + "].level"] = item.level;
              if (!['datacenter_air', 'datacenter_ups'].includes(item.meter)) {
                postData["subhealthThresholds[" + index + "].lowerThreshold"] = values['lowerThreshold_' + item.id];
              }
              postData["subhealthThresholds[" + index + "].meter"] = item.meter;
              postData[
                "subhealthThresholds[" + index + "].resourceId"
              ] = this.model.id;
              postData["subhealthThresholds[" + index + "].type"] = this.type;
              postData["subhealthThresholds[" + index + "].upperThreshold"] = values['upperThreshold_' + item.id];
              index++;
            });
            gPostAction("/subhealth/setThreshold", postData).then((res) => {
              if (res.success) {
                this.$message.success("操作成功");
                this.$emit("ok");
              }
            }).finally(() => {
              this.handleCancel();
            })
          }
        })
      },
      handleCancel(e) {
        this.confirmLoading = false;
        this.visible = false;
      },
      upperThresholdValidator(rule, value, callback, id) {
        value > this.form.getFieldValue('lowerThreshold_' + id) ? callback() : callback('最大值需大于最小值')
      },
      lowerThresholdValidator(rule, value, callback, id) {
        value < this.form.getFieldValue('upperThreshold_' + id) ? callback() : callback('最小值需小于最大值')
      },
      getRange(meter) {
        const range = {
          min: 0,
          max: 99999,
        }
        if (['environment.air_out_humidity', 'environment.air_in_humidity'].includes(meter)) {
          range.max = 100
        } else if (['environment.air_in_temperature', 'environment.air_out_temperature', 'environment.ups_temperature'].includes(meter)) {
          range.min = 0.01
          range.max = 100
        } else if (['environment.ups_in_voltage', 'environment.ups_out_voltage'].includes(meter)) {
          range.max = 500
        }
        return range
      },
    },
  };
</script>

<style scoped>
</style>